<template>
  <div class="content">
    <div style="boxs">
      <!-- <Header :params="params" /> -->
    </div>
    <div class="body">
      <div class="tips">请添加上传文件：</div>
      <van-uploader ref="uploader" :before-read="beforeRead" :after-read="afterRead" :preview-full-image="false" @delete="preDel" @click-preview="previewFile" v-model="fileList" accept="video/mp4,video/quicktime,video/avi,video/3gpp" max-count="1" />
      <div class="button">
        <van-button type="info" :disabled="flag" @click="uploadFile">提交</van-button>
        <!-- <van-button loading type="info" loading-text="加载中...">提交</van-button> -->
      </div>
    </div>
    <!-- 视频预览 -->
    <div v-if="show" @click="cancelVideo" class="videoMask">
      <div class="wrapper">
        <div>
          <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true" :options="playerOptions">
          </video-player>
        </div>
      </div>
    </div>
    <!-- 进度条 -->
    <div class="percentage">
      <van-progress :percentage="percentage" :show-pivot="false" />
    </div>
  </div>
</template>
<script>
const qiniu = require("qiniu-js");
import Header from "@/components/Header.vue";
export default {
  components: {
    Header,
  },
  data() {
    return {
      params: {
        left: true,
        title: "文件上传",
      },
      percentage: 0,
      flag: true,
      fileList: [],
      fileLists: [],
      // 视频预览
      show: false,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], //倍速控制
        autoplay: false, //是否自动播放
        muted: false, //是否静音播放
        loop: false, //是否循环播放
        preload: "auto",
        language: "zh-CN", //语言，还要引入对应的文件
        aspectRatio: "16:9", //比例
        fluid: true,
        sources: [
          {
            type: "",
            src:
              "http://niu.icrobot.cn/ce468e3dda7c4d6a99dab17a517e77ad3-005-008%E8%AF%BE%E5%89%8D%E5%A4%8D%E4%B9%A0.mp4", //url地址
          },
        ],
        poster: "", //你的封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试",
        controlBar: {
          timeDivider: true,
          durationDisplay: true, //剩余时间是否显示
          remainingTimeDisplay: false, //剩余时间是否显示，有一个即可
          fullscreenToggle: true, //全屏按钮
        },
      },
      formData: "",
      taskId: "",
      status: "",
      token: "",
    };
  },
  mounted() {
    this.taskId = this.$route.query.id;
    this.status = this.$route.query.status;
    this.queryToken();
  },
  methods: {
    queryToken() {
      (async () => {
        const res = await this.get("/approve/tokenResult");
        this.token = res.msg;
      })();
    },
    // 上传之前的校验
    beforeRead(file) {
      if (
        file.type !== "video/mp4" &&
        file.type !== "video/quicktime" &&
        file.type !== "video/avi" &&
        file.type !== "video/3gpp"
      ) {
        this.$toast.fail("上传视频格式有误");
        return false;
      }
      if (file.size / 1024 / 1024 >= 100) {
        this.$toast.fail("上传视频文件不能大于100M");
        return false;
      }
      //获取视频时长
      // let videoUrl = URL.createObjectURL(file);
      // let audioElement = new Audio(videoUrl);
      // audioElement.addEventListener("loadedmetadata", () => {
      //   let duration = audioElement.duration; //时长为秒，小数，182.36
      //   file.fileTime = Math.floor(duration);
      // });
      this.fileLists = [];
      this.fileLists.push(file);
      return true;
    },
    // 上传成功
    afterRead() {
      // 预览图
      // let obj = {};
      // obj.url="/img/videoTask/videoListImg.png";
      // this.fileList.push(obj);
      if (this.fileList.length > 0) {
        this.flag = false;
      } else {
        this.flag = true;
      }
    },
    // 删除预览
    preDel() {
      if (this.fileList.length > 0) {
        this.flag = false;
      } else {
        this.flag = true;
      }
    },
    // 点击预览图片
    previewFile() {
      this.$toast.fail("视频文件不支持预览");
    },
    // 上传视频文件
    uploadFile() {
      var that = this;
      this.formData = new FormData();
      this.flag = true;
      // file
      // this.formData.append(`fileList[0].file`, this.fileLists[0]);

      // 先把文件以分块的形式上传给七牛云  再把id和fileName给后台
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2,
      };
      const putExtra = {
        fname: "qiniu.txt",
        mimeType: "video/mp4",
        customVars: { "x:test": "qiniu" },
        metadata: { "x-qn-meta-": "qiniu" },
      };
      const observer = {
        next(res) {
          console.log(res);
          that.percentage = res.total.percent;
          if (res.total.percent == 100) {
            // fileName
            that.formData.append(
              `fileList[0].fileName`,
              that.fileLists[0].name
            );
            // id
            that.formData.append("id", that.taskId);
            // key
            that.formData.append("fileList[0].key", "/app2/" + that.fileLists[0].lastModified + that.fileLists[0].name);
            // 待提交上传
            if (that.status == "已驳回") {
              that.uploadFinalFile1();
              this.flag = false;
            } else if (that.status == "待提交") {
              that.uploadFinalFile();
              this.flag = false;
            }
            // 已驳回重新上传
          }
        },
        error(err) {
          // ...
        },
        complete(res) {
          // ...
        },
      };
      const observable = qiniu.upload(
        this.fileLists[0],
        "/app2/" + this.fileLists[0].lastModified + this.fileLists[0].name,
        this.token,
        putExtra,
        config
      );
      const subscription = observable.subscribe(observer);
    },
    // 待提交上传
    uploadFinalFile() {
      this.$toast.loading({
        message: "上传中...",
        forbidClick: true,
        duration: 0,
      });
      (async () => {
        const data = await this.post("/approve/addBeiKeVideo", this.formData);
        if (data.code == 200) {
          this.$toast.clear();
          this.$toast({
            message: data.msg,
            duration: 1000,
            type: "success",
            onClose: () => {
              this.$router.back();
            },
          });
        } else {
          this.$toast.clear();
          this.$toast({
            message: data.msg,
            duration: 1000,
            type: "fail",
          });
        }
      })();
    },
    // 已驳回重新上传
    uploadFinalFile1() {
      this.$toast.loading({
        message: "上传中...",
        forbidClick: true,
        duration: 0,
      });
      (async () => {
        const data = await this.post(
          "/approve/beiKeVideoReuploadHasBeenRejected",
          this.formData
        );
        if (data.code == 200) {
          this.$toast.clear();
          this.$toast({
            message: data.msg,
            duration: 1000,
            type: "success",
            onClose: () => {
              this.$router.go(-2);
            },
          });
        } else {
          this.$toast.clear();
          this.$toast({
            message: data.msg,
            duration: 1000,
            type: "fail",
          });
        }
      })();
    },
    // 视频预览
    preVideo() {
      this.$toast.loading({
        message: "加载中",
        duration: 500,
        onClose: () => {
          this.show = true;
        },
      });
    },
    // 取消视频预览
    cancelVideo() {
      this.show = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.boxs {
  width: 100%;
}
.content {
  width: 100%;
  height: 100%;
  background-color: #f7f9fa;
  position: relative;
  .percentage {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  .body {
    width: 100%;
    height: 100%;
    background-color: #fff;
    font-size: 0.1rem;
    padding: 0.3rem 0.24rem 0;
    box-sizing: border-box;
    position: relative;
    .tips {
      font-size: 0.28rem;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
      margin-bottom: 0.24rem;
    }
    .button {
      position: absolute;
      left: 0.24rem;
      bottom: 0.24rem;
      .van-button {
        width: 7.02rem;
        height: 0.84rem;
      }
    }
  }
  .videoMask {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    .wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      div {
        width: 100%;
      }
    }
  }
}
.van-uploader__preview {
  margin-right: 0 !important;
}
</style>